﻿using Microsoft.Extensions.Hosting;
using SuperSocket.Server;
using SuperSocket.Server.Abstractions;
using SuperSocket.Server.Host;
using SuperSocket.WebSocket.Server;

namespace SuperSocket2._0Demo
{
    internal class Program
    {
        static async Task Main(string[] args)
        {
            WebSockSvr server = new WebSockSvr();
            await server.Start();

            server.SendDatas();
            Console.ReadLine();
        }
    }

    public class WebSockSvr
    {
        public List<WebSocketSession> ClinetList { get; set; } = new();
        private IServer server;
        public WebSockSvr()
        {
            server = WebSocketHostBuilder.Create()
                .ConfigureSuperSocket(opts =>
                {
                    opts.AddListener(new ListenOptions
                    {
                        Ip = "127.0.0.1",
                        Port = 4040
                    });
                })
                .UseSessionHandler((session) =>
                {
                    var sess = (WebSocketSession)session;
                    ClinetList.Add(sess);
                    return ValueTask.CompletedTask;
                }, (session, reason) =>
                {
                    var sess = (WebSocketSession)session;
                    ClinetList.Remove(sess);
                    return ValueTask.CompletedTask;
                })
                .UseWebSocketMessageHandler(async (session, message) =>
                {
                })
                .BuildAsServer();
        }
        public Task Start()
        {
            return server.StartAsync();
        }
        public void SendDatas()
        {
            for (int i = 0; i < 200; i++)
            {
                Task.Run(async () =>
                {
                    while (true)
                    {
                        try
                        {
                            for (int j = 0; j < ClinetList.Count; j++)
                            {
                                var sock = ClinetList[j];
                                if (sock.State == SessionState.Connected)
                                {
                                    await sock.SendAsync($"Dev[{DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss:fff")}, 12.34, 34.56, 56.78, \"77705683\"]");
                                }
                            }
                        }
                        catch (Exception ex)
                        {
                            Console.WriteLine("出现异常：" + ex.Message + "\r\n" + ex.StackTrace);
                        }
                        finally
                        {
                            await Task.Delay(10);
                        }
                    }
                });
            }

        }
    }
}
